package com.woniuxy.config;

import com.woniuxy.filter.JwtAuthenticationFilter;
import com.woniuxy.service.impl.AccessDeniedHandlerImpl;
import com.woniuxy.service.impl.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableGlobalMethodSecurity(prePostEnabled = true)

@Configuration

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;


@Bean
//启用加密
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();



}
@Bean
    @Override
//配置认证管理器
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.csrf().disable()  //禁用跨站请求伪造，前后端分离的程序没有这种问题response
              .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
              .and()
              .authorizeRequests()
              .antMatchers("**").anonymous()   //登陆页面不拦截
              .anyRequest().authenticated();
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

 http.exceptionHandling()
         .authenticationEntryPoint(new AuthenticationEntryPointImpl())
         .accessDeniedHandler(new AccessDeniedHandlerImpl());

http.cors();
    }

}
